package com.ldj.tim.client.service.impl.command;

import com.ldj.tim.client.config.AppConfiguration;
import com.ldj.tim.client.service.EchoService;
import com.ldj.tim.client.service.InnerCommand;
import com.ldj.tim.client.service.MsgLogger;
import com.ldj.tim.common.constant.CacheConstants;
import com.ldj.tim.common.pojo.BasicMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 *
 * @since JDK 1.8
 */
@Service
public class QueryHistoryCommand implements InnerCommand {
    private final static Logger LOGGER = LoggerFactory.getLogger(QueryHistoryCommand.class);

    @Autowired
    private RedisTemplate<String, BasicMessage> redisTemplate;

    @Autowired
    private AppConfiguration configuration;

    @Autowired
    private MsgLogger msgLogger ;

    @Autowired
    private EchoService echoService ;

    @Override
    public void process(String msg) {
        String[] split = msg.split(" ");
        if (split.length < 2){
            return;
        }
        //从本地文件中获取
//        String res = msgLogger.query(split[1]);
//        echoService.echo(res);
        //从缓存中拉取最新历史记录
        String key = CacheConstants.OFFLINE_MSG+configuration.getUserId()+":"+split[1];
        Set<BasicMessage> offlineMsg = redisTemplate.opsForZSet().range(key, 0, -1);
        if (offlineMsg.isEmpty()) return;
        for (BasicMessage message : offlineMsg) {
            echoService.echo(message.getMessage());
        }
        //获取成功后从换从中删除
        redisTemplate.opsForZSet().removeRange(key, 0, -1);
    }
}
